<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import BaseInfo from '@/components/pages/order/good-settle-create/BaseInfo.vue'
  import FeeStandards from '@/components/pages/order/good-settle-create/fee-standards/Index.vue'
  import infoTip from '@/config/info-tip'
  import { nextTick, onMounted, ref } from 'vue'
  import { useForm } from '@/services/pages/order/useGoodSettle'
  import { useRoute, useRouter } from 'vue-router'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import { useActiveTab } from '@/services/pages/order/set'
  import { useGetGoodSettleDetail } from '@/services/pages/order/useGoodSettle'
  import routeComponentName from '@/config/route-component-name'

  const { form, resetForm, save } = useForm()
  const { setActiveTab, setFeeCostActiveTab } = useActiveTab()
  const { detail, loading, getDetail } = useGetGoodSettleDetail()

  defineOptions({
    name: routeComponentName.order.goodSettleForm,
  })

  const tagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const chargeStandardType = ref<1 | 2>(1)
  const feeStandardMode = ref<'good' | 'goodType'>('good')
  const baseInfoInstance = ref<InstanceType<typeof BaseInfo> | null>(null)
  const feeStandardsInstance = ref<InstanceType<typeof FeeStandards> | null>(null)

  // 支付部门费用
  const payNetworkFee = ref('0')

  /**
   * 方案类型更新事件
   * @param type 1：按设备名称、2：按设备类型
   */
  const handleChargeStandardTypeChange = (type: 1 | 2) => {
    chargeStandardType.value = type
    form.value.programmeFeeVos = []
    form.value.delSettlementProgrammeIds = []

    switch (type) {
      case 1:
        feeStandardMode.value = 'good'
        break
      case 2:
        feeStandardMode.value = 'goodType'
        break
    }
    nextTick(() => {
      if (feeStandardsInstance.value) {
        feeStandardsInstance.value.setNetworkPayPrice(payNetworkFee.value)
      }
    })
  }

  /**
   * 提交事件
   */
  const onSubmit = async () => {
    if (baseInfoInstance.value && feeStandardsInstance) {
      const _form = await baseInfoInstance.value.getForm()
      const feeStandards = feeStandardsInstance.value.getList()
      if (!_form) {
        return
      }

      if (!feeStandards) {
        return
      }

      if (feeStandards.length === 0) {
        switch (chargeStandardType.value) {
          case 1:
            HMessageBox.error(infoTip.order.goodSettle.noSelectGood)
            break
          case 2:
            HMessageBox.error(infoTip.order.goodSettle.noSelectGoodType)
            break
        }
        return
      }

      form.value.descr = _form.descr
      form.value.moduleIds = _form.moduleIds
      form.value.name = _form.name
      form.value.status = _form.status
      form.value.type = _form.type
      form.value.programmeFeeVos = feeStandards
      form.value.id = _form.id
      form.value.delSettlementProgrammeIds = feeStandardsInstance.value.getRemoveFeeStandardIds()

      const res = await save()
      if (res.code === 20000) {
        HMessage.success(infoTip.order.goodSettle.formSaveSuccess)
        tagsViewStore.delView(route.path)
        router.back()
        resetForm()
        setActiveTab('cost')
        setFeeCostActiveTab('goodSettleSet')
        return
      }

      HMessageBox.error(infoTip.order.goodSettle.err_code[res.code] || res.message)
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    if (baseInfoInstance.value) {
      baseInfoInstance.value.resetForm()
      tagsViewStore.delView(route.path)
      router.back()
      resetForm()
      setActiveTab('cost')
      setFeeCostActiveTab('goodSettleSet')
    }
  }

  /**
   * 支付部门费用输入事件
   * @param {String} price - 部门费用
   */
  const handleChangePayNetworkPrice = (price: string) => {
    payNetworkFee.value = price
    if (feeStandardsInstance.value) {
      feeStandardsInstance.value.setNetworkPayPrice(price)
    }
  }

  onMounted(async () => {
    if (route.params.id) {
      await getDetail(route.params.id as string)
      handleChargeStandardTypeChange(detail.value.type)
    }

    if (baseInfoInstance.value) {
      await baseInfoInstance.value.getModuleOptions()
      baseInfoInstance.value.setForm({
        ...detail.value,
        programmeFeeVos: detail.value.programmeFeeVos.map((item) => {
          return { ...item, payNetworkFee: String(item.payNetworkFee) }
        }),
      })
      if (detail.value.programmeFeeVos[0]) {
        baseInfoInstance.value.setPayNetworkPrice(
          String(detail.value.programmeFeeVos[0].payNetworkFee),
        )
      } else {
        baseInfoInstance.value.setPayNetworkPrice('0')
      }
    }

    if (feeStandardsInstance.value) {
      feeStandardsInstance.value.setList(detail.value.programmeFeeVos)
    }
  })
</script>

<template>
  <div v-loading="loading" class="commodity-settle-create-wrapper">
    <div class="commodity-settle-create">
      <div class="header">
        <div class="title">添加设备结算方案</div>
      </div>

      <div class="divider"></div>

      <div class="base-info">
        <base-info
          ref="baseInfoInstance"
          @type-change="handleChargeStandardTypeChange"
          @change-pay-network-price="handleChangePayNetworkPrice"
        ></base-info>
      </div>

      <div class="list-wrapper">
        <div class="charge-standards">
          <fee-standards ref="feeStandardsInstance" :mode="feeStandardMode"></fee-standards>
        </div>
        <div class="btn-group">
          <h-button is-modal type="primary" @click="onSubmit">保存</h-button>
          <h-button is-modal @click="onCancel">取消</h-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .commodity-settle-create-wrapper {
    height: calc(100vh - 92px);
    width: 100%;
    box-sizing: border-box;
    padding: 12px;

    .commodity-settle-create {
      height: 100%;
      width: 100%;
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      display: flex;
      flex-direction: column;

      .header {
        padding: 0 12px;

        .title {
          font-size: 14px;
          font-weight: bold;
        }
      }

      .divider {
        border-bottom: 1px dotted #e5e5e5;
        margin: 12px 0;
      }

      .base-info {
        box-sizing: border-box;
        padding: 0 12px;
      }

      .list-wrapper {
        width: 100%;
        flex: 1;
        box-sizing: border-box;
        padding: 24px 12px 0 12px;
        height: 0;
        display: flex;
        row-gap: 12px;
        flex-direction: column;

        .network-settles,
        .charge-standards {
          max-height: calc(100% - 40px);
        }

        .btn-group {
          display: flex;
          justify-content: center;
          column-gap: 10px;
        }
      }
    }
  }
</style>
